import re
from collections import defaultdict
class 表达式解析器:
    def 解析条件(self, cond_str):
        """解析单个条件（如 A≥3、(A+B)≥5、≥10）"""
        cond_str = cond_str.replace(' ', '')

        # 1. 总数量条件: ≥10
        match = re.match(r"(?:≥|>=)(\d+)", cond_str)
        if match:
            return {"type": "total", "min": int(match.group(1))}

        # 2. 单类型条件: A≥3
        if "(" not in cond_str:
            match = re.match(r"(\w+)(?:≥|>=)(\d+)", cond_str)
            if match:
                return {"type": "single", "card": match.group(1), "min": int(match.group(2))}

        # 3. 组合条件: (A+B)≥5
        if cond_str.startswith("("):
            match = re.match(r"\(([\w+]+)\)(?:≥|>=)(\d+)", cond_str)
            if match:
                cards = match.group(1).split("+")
                return {"type": "combined", "cards": cards, "min": int(match.group(2))}

        raise ValueError(f"无法解析条件: {cond_str}")


    def 评估条件(self, cond, card_counts, total_cards):
        """检查单个条件是否满足"""
        if cond["type"] == "total":
            return total_cards >= cond["min"]
        elif cond["type"] == "single":
            return card_counts.get(cond["card"], 0) >= cond["min"]
        elif cond["type"] == "combined":
            total = sum(card_counts.get(card, 0) for card in cond["cards"])
            return total >= cond["min"]
        return False


    def _评估单行表达式(self, expr_line, card_counts, total_cards):
        """解析并计算单行逻辑表达式"""
        # 1. 提取所有条件并用占位符替换
        total_cond_pattern = r"(?:≥|>=)\d+"
        single_cond_pattern = r"\w+(?:≥|>=)\d+"
        combined_cond_pattern = r"\(([\w+]+)\)(?:≥|>=)(\d+)"

        all_cond_patterns = [combined_cond_pattern, single_cond_pattern, total_cond_pattern]

        conditions_map = {}
        placeholder_idx = 0
        processed_expr = expr_line

        for pattern in all_cond_patterns:
            matches = []
            for match in re.finditer(pattern, processed_expr):
                matches.append(match)

            for match in reversed(matches):
                cond_str = match.group(0)
                if cond_str not in conditions_map:
                    placeholder = f"COND_{placeholder_idx}"
                    conditions_map[cond_str] = placeholder
                    placeholder_idx += 1
                else:
                    placeholder = conditions_map[cond_str]

                processed_expr = processed_expr[:match.start()] + placeholder + processed_expr[match.end():]

        # 2. 评估每个条件
        evaluated_conditions = {}
        for cond_str, placeholder in conditions_map.items():
            cond = self.解析条件(cond_str)
            evaluated_conditions[placeholder] = self.评估条件(cond, card_counts, total_cards)

        # 3. 替换占位符为布尔值并评估最终逻辑表达式
        final_logical_expr = processed_expr
        for placeholder, value in evaluated_conditions.items():
            final_logical_expr = final_logical_expr.replace(placeholder, str(value))

        # 替换比较运算符
        final_logical_expr = final_logical_expr.replace("≥", ">=")

        # 替换逻辑运算符
        final_logical_expr = final_logical_expr.replace("&&", " and ").replace("||", " or ")

        return eval(final_logical_expr)


    def 评估表达式(self, multi_line_expr, card_pile):
        """解析并计算多行逻辑表达式"""
        card_counts = defaultdict(int)
        for card in card_pile:
            card_counts[card] += 1
        total_cards = len(card_pile)

        expressions = multi_line_expr.replace(' ','').split('\n')
        for expr_line in expressions:
            if not expr_line.strip():  # Skip empty lines
                continue
            if self._评估单行表达式(expr_line, card_counts, total_cards):
                return True
        return False

    def 验证表达式(self, multi_line_expr):
        """
        验证多行表达式的语法和逻辑。
        返回 (True, None) 如果表达式有效，否则返回 (False, 错误信息)。
        """
        expressions = multi_line_expr.replace(' ','').split('\n')
        if not expressions:
            return False,"请输入条件上传表达式"
        for i, expr_line in enumerate(expressions):
            if not expr_line.strip():
                continue
            try:
                # 尝试解析条件
                # 这里我们不需要实际的card_counts和total_cards，只需要确保语法正确
                # 我们可以使用一个虚拟的card_counts和total_cards来避免运行时错误
                dummy_card_counts = {}
                dummy_total_cards = 0
                self._评估单行表达式(expr_line, dummy_card_counts, dummy_total_cards)
            except ValueError as e:
                return False, f"第 {i+1} 行条件解析错误: {e}"
            except SyntaxError as e:
                return False, f"第 {i+1} 行表达式语法错误: {e}"
            except Exception as e:
                return False, f"第 {i+1} 行未知错误: {e}"
        return True, None

if __name__ == '__main__':
    # # 测试用例
    # test_cases = [
    #     (["A", "A", "B"], "A≥2 && B≥1", True),
    #     (["A", "B", "C"], "A≥2 || B≥2", False),
    #     (["A", "A", "B", "B"], "(A+B)≥3 && C≥1", False),
    #     (["A", "A", "B", "C"], "≥4 && (A+B)≥3", True),
    #     # 新增多行表达式测试用例
    #     (["A", "A", "B", "C"], "A≥2\nB≥1", True),  # A>=2 AND B>=1
    #     (["A", "A", "B", "C"], "A≥3\nB≥1", False),  # A>=3 is False, so overall False
    #     (["A", "A", "B", "C"], "A≥2\nC≥1\n(A+B)≥3", True),  # All true
    #     (["A", "A", "B", "C"], "A≥2\nC≥2", False),  # C>=2 is False
    # ]
    test_cases=[
        (['雷伊潔兒','妍熙','艾斯','尼亞','妍熙','太烏','太烏','太烏','太烏'],'太烏>=2 && 妍熙≥1',True),
        (['雷伊潔兒','艾斯','毗曇','太烏','太烏'], '菲依>=1 || 蘿希>=1 || 朱里 >=1 || 太烏>=2', True),
        #(["A", "A", "B", "C"], "≥4 && (A+B)≥3", True),
    ]
    parser = 表达式解析器()

    # print("测试结果:")
    # for cards, expr, expected in test_cases:
    #     erro = parser.验证表达式(expr)
    #     result = parser.评估表达式(expr, cards)
    #     processed_expr_for_print = expr.replace('\n', ' \\n ')
    #     output_str = "{} | {} -> {} (预期: {}, 实际: {})".format(
    #         cards,
    #         processed_expr_for_print,
    #         '通过' if result == expected else '失败',
    #         expected,
    #         result
    #     )
    #     print(output_str)

